package com.huang.springbootthymeleafshiro.shiro.redis;

import com.huang.springbootjspshiro.utils.ApplicationContextUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Collection;
import java.util.Set;

public class RedisCache<k,v> implements Cache<k,v> {

    private  String authName;

    public RedisCache() {

    }

    public RedisCache(String authName) {
        this.authName = authName;
    }

    public RedisTemplate getRedis(){
        RedisTemplate redisTemplate =(RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Override
    public v get(k k) throws CacheException {
        RedisTemplate redisTemplate = getRedis();
        return (v) redisTemplate.opsForValue().get(k.toString());
    }

    @Override
    public v put(k k, v v) throws CacheException {
        RedisTemplate redisTemplate = getRedis();
        //存入redis  map形式 （认证授权的名字，（用户名，权限））
        redisTemplate.opsForHash().put(this.authName,k.toString(),v);

        return null;
    }

    @Override
    public v remove(k k) throws CacheException {
        RedisTemplate redisTemplate = getRedis();
        System.out.println(";;;;remove");
        return (v) redisTemplate.opsForHash().delete(this.authName,k.toString());
    }

    @Override
    public void clear() throws CacheException {
        RedisTemplate redisTemplate = getRedis();
        System.out.println(";;;;clear");
       redisTemplate.opsForHash().delete(this.authName);
    }

    @Override
    public int size() {
        return getRedis().opsForHash().size(this.authName).intValue();
    }


    @Override
    public Set<k> keys() {
        return getRedis().opsForHash().keys(this.authName);
    }

    @Override
    public Collection<v> values() {
        return getRedis().opsForHash().values(this.authName);
    }

}
